//@ts-check
'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')

const { BannerPlugin } = require('webpack');

// Webpack通知插件
const WebpackNotifierPlugin = require('webpack-notifier');
// TS类型检查插件(可用于JS，需要在文件头上加`//@ts-check`)
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
// TS类型检查通知插件，配合ForkTsCheckerWebpackPlugin使用
const ForkTsCheckerNotifierWebpackPlugin = require('fork-ts-checker-notifier-webpack-plugin');
// 打包分析插件，默认端口8888
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// 梁非凡
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following method:
// port = 9527 npm run dev OR npm run dev --port = 9527
const port = 8899 // dev port


// All configuration item explanations can be find in https://cli.vuejs.org/config/
/**
 * @type {import('@vue/cli-service').ProjectOptions}
 */
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: false,
  productionSourceMap: false,
  devServer: {
    host: "0.0.0.0",
    port,
    compress: true,
    open: false,
    disableHostCheck: true,
    overlay: {
      warnings: false,
      errors: true
    },
    before: process.env.ENV === "mock" ? require('./mock/mock-server.js') : undefined,
    proxy: {
      "/env": {
        target: "http://134.96.252.42:8000",
        changeOrigin: true,
        pathRewrite: {
          "^/env": ""
        }
      }
    }
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name,
    entry: "./src/main.ts",
    devtool: "source-map",
    resolve: {
      alias: {
        '@': resolve('src')
      },
    },
  },

  /**
   * @param {import("webpack-chain")} config
   */
  chainWebpack(config) {

    console.log("\n");

    console.warn('\x1B[36m%s\x1B[0m', "NODE_ENV = " + process.env.NODE_ENV);
    console.warn('\x1B[36m%s\x1B[0m', "VUE_APP_API = " + process.env.VUE_APP_API);

    console.log("\n");

    // Webpack 处理的文件类型
    config.resolve.extensions.merge([".js", ".ts", ".vue", ".json"]);
    config.when(process.env.NODE_ENV === 'development', config => {
      config.plugin("BundleAnalyzerPlugin").use(BundleAnalyzerPlugin, [{ openAnalyzer: false }]);
      console.log("\x1B[42m%s\x1B[0m", "[+] BundleAnalyzer Plugin Loaded.")
      config.plugin("CleanWebpackPlugin").use(CleanWebpackPlugin, [{ verbose: true }]);
      console.log("\x1B[42m%s\x1B[0m", "[+] CleanWebpack Plugin Loaded.")
    });

    config.plugin("ForkTsCheckerWebpackPlugin").use(ForkTsCheckerWebpackPlugin);
    console.log("\x1B[42m%s\x1B[0m", "[+] ForkTsCheckerWebpack Plugin Loaded.")
    config.plugin("WebpackNotifierPlugin").use(WebpackNotifierPlugin, [{ title: "Webpacker", emoji: true }]);
    console.log("\x1B[42m%s\x1B[0m", "[+] WebpackNotifier Plugin Loaded.")
    config.plugin("ForkTsCheckerNotifierWebpackPlugin").use(ForkTsCheckerNotifierWebpackPlugin, [{ excludeWarnings: true }]);
    console.log("\x1B[42m%s\x1B[0m", "[+] ForkTsCheckerNotifierWebpack Plugin Loaded.")

    // TypeScript 装载器
    config.module
      .rule('typescript')
      .test(/\.tsx?$/)
      .exclude.add(/node_modules/)
      .end()
      .use('ts-loader')
      .loader('ts-loader')
      .options({
        appendTsSuffixTo: [/\.vue$/],
      })
      .end()
    console.log("\x1B[42m%s\x1B[0m", "[+] TypeScript Loader Ready.")


    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])
    console.log("\x1B[42m%s\x1B[0m", "[+] Preload Plugin Loaded.")

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')
    console.log("\x1B[42m%s\x1B[0m", "[-] Prefetch Plugin Unloaded.")

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
    console.log("\x1B[42m%s\x1B[0m", "[+] Svg Sprite Loader Ready.")

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {

          config.plugin("BannerPlugin").use(BannerPlugin, [{ banner: "(赤)斥资打造, 耗时三年, 五毛一条. 开发者: github.com/sdttttt" }])
          console.log("\x1B[42m%s\x1B[0m", "[+] Banner Plugin Loaded.")

          config.performance.maxAssetSize(30000000);
          config.performance.maxEntrypointSize(10000000);

          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          console.log("\x1B[42m%s\x1B[0m", "[+] ScriptExtHtmlWebpack Plugin loaded.")
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          console.log("\x1B[42m%s\x1B[0m", "[+] splitChunks Plugin loaded.")
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')
          console.log("\x1B[42m%s\x1B[0m", "[+] RuntimeChunk Plugin loaded.")
          console.log();
        }
      )
  }
}
